package com.king.photo.activity;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.bean.BlogToSendBean;
import com.example.day.OneDatyPerson;
import com.example.global.Constant;
import com.example.jhf.R;
import com.example.space.AnswerPer;
import com.example.space.Class_Question;
import com.example.space.Class_questionAapter;
import com.example.space.QuestionDetail;
import com.example.space.Show;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.baseadapter.utils.BitmapUtils;
import com.imooc.baseadapter.utils.Tools;
import com.king.photo.util.Bimp;
import com.king.photo.util.FileUtils;
import com.king.photo.util.ImageItem;
import com.king.photo.util.PublicWay;
import com.king.photo.util.Res;

public class MainActivitypoth extends Activity {

	private GridView noScrollgridview;
	private GridAdapter adapter;
	private View parentView;
	private PopupWindow pop = null;
	private LinearLayout ll_popup;
	public static Bitmap bimap;
	private ObjectMapper om = new ObjectMapper();
	private String code;
	private ArrayList<CItem> lst;
	private String id = "1";// 被单击的id
	private String noteStr = "";// 问题内容
	private String string = "";// 图片字串
	private static final String FILE_NAME = "USER_NOTE";
	private Editor edit;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// if (savedInstanceState != null) {
		// noteStr = savedInstanceState.getString("Note");
		// }
		SharedPreferences sharedPreferences = getSharedPreferences(FILE_NAME,
				Activity.MODE_PRIVATE);
		String note = sharedPreferences.getString("Value", "");
		System.out.println(note);
		// etBlog.setText(note);F
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		Res.init(this);
		bimap = BitmapFactory.decodeResource(getResources(),
				R.drawable.icon_addpic_unfocused);
		PublicWay.activityList.add(this);
		parentView = getLayoutInflater().inflate(
				R.layout.activity_selectimgtwo, null);

		setContentView(parentView);
		getJsonText();
		spinner = (Spinner) findViewById(R.id.spinner_questionid);
		Init();
		etBlog.setText(note);
	}

	// @Override
	// protected void onStart() {
	// // TODO Auto-generated method stub
	// super.onStart();
	// }
	public void Init() {
		tvSend = (TextView) findViewById(R.id.activity_selectimg_send_id);
		etBlog = (EditText) findViewById(R.id.activity_selectimg_send_idid);

		/**
		 * 得到博客内容、图片列表 传输数据？
		 */
		tvSend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				ArrayList<BlogToSendBean> images = new ArrayList<BlogToSendBean>();
				for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
					String image = BitmapUtils
							.convertBitmapToString(Bimp.tempSelectBitmap.get(i)
									.getBitmap());
					String title = Math.random() * 1000 + ".jpg";
					images.add(new BlogToSendBean(title, image));
				}

				try {
					string = om.writeValueAsString(images);
				} catch (JsonProcessingException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				noteStr = etBlog.getText().toString().trim();
				if (noteStr.length() != 0 || string.length() != 0) {
					sendJsontoNet();
				} else {
					Toast.makeText(getApplicationContext(), "您好，内容不能为空！",
							Toast.LENGTH_SHORT).show();
				}

			}
		});
		pop = new PopupWindow(MainActivitypoth.this);

		View view = getLayoutInflater().inflate(R.layout.item_popupwindows,
				null);

		ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);

		pop.setWidth(LayoutParams.MATCH_PARENT);
		pop.setHeight(LayoutParams.WRAP_CONTENT);
		pop.setBackgroundDrawable(new BitmapDrawable());
		pop.setFocusable(true);
		pop.setOutsideTouchable(true);
		pop.setContentView(view);

		RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
		Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
		Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);
		Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);
		parent.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});
		bt1.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				photo();
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});
		bt2.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(MainActivitypoth.this,
						AlbumActivity.class);
				// Intent intent = new Intent(MainActivitypoth.this,
				// CopyOfAlbumActivity.class);
				startActivity(intent);
				overridePendingTransition(R.anim.activity_translate_in,
						R.anim.activity_translate_out);
				pop.dismiss();
				ll_popup.clearAnimation();
				finish();
			}
		});
		bt3.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});

		noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
		noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new GridAdapter(this);
		adapter.update();
		noScrollgridview.setAdapter(adapter);
		noScrollgridview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				noteStr = etBlog.getText().toString().trim();
				SharedPreferences sharedPreferences = getSharedPreferences(
						FILE_NAME, Activity.MODE_PRIVATE);
				edit = sharedPreferences.edit();
				edit.putString("Value", noteStr);
				edit.commit();
				// 隐藏输入法
				((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
						.hideSoftInputFromWindow(MainActivitypoth.this
								.getCurrentFocus().getWindowToken(),
								InputMethodManager.HIDE_NOT_ALWAYS);
				if (arg2 == Bimp.tempSelectBitmap.size()) {
					Log.i("ddddddd", "----------");
					ll_popup.startAnimation(AnimationUtils
							.loadAnimation(MainActivitypoth.this,
									R.anim.activity_translate_in));
					pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
				} else {
					Intent intent = new Intent(MainActivitypoth.this,
							GalleryActivity.class);
					intent.putExtra("position", "1");
					intent.putExtra("ID", arg2);
					startActivity(intent);
				}
			}
		});

	}

	/**
	 * 发送到后台
	 */
	protected void sendJsontoNet() {
		// TODO Auto-generated method stub
		final Handler handler = new Handler() {

			public void handleMessage(Message msg) {
				if (msg.what == 7) {
					SharedPreferences sharedPreferences = getSharedPreferences(
							FILE_NAME, Activity.MODE_PRIVATE);
					Editor edit2 = sharedPreferences.edit();
					edit2.putString("Value", "");
					edit2.commit();
					Toast.makeText(getApplicationContext(), "发表成功！", 0).show();
					// noScrollgridview.removeAllViews();
					for (int i = 0; i < PublicWay.activityList.size(); i++) {
						if (null != PublicWay.activityList.get(i)) {
							PublicWay.activityList.get(i).finish();
						}
					}
					System.exit(0);
					// noScrollgridview.
					// finish();
					// getJsonText();
				} else if (msg.what == 6) {
					Toast.makeText(getApplicationContext(), "发表失败！", 0).show();
				} else if (msg.what == 10) {
					Toast.makeText(getApplicationContext(), "评论消失在二次元", 0)
							.show();
				}
			}

		};
		new Thread() {
			public void run() {
				// ArrayList<BlogToSendBean> images = new
				// ArrayList<BlogToSendBean>();
				// for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
				// String image = BitmapUtils
				// .convertBitmapToString(Bimp.tempSelectBitmap.get(i)
				// .getBitmap());
				// String title = Math.random() * 1000 + ".jpg";
				// images.add(new BlogToSendBean(title, image));
				// }
				//
				// try {
				// string = om.writeValueAsString(images);
				// } catch (JsonProcessingException e1) {
				// // TODO Auto-generated catch block
				// e1.printStackTrace();
				// }
				// 设置参数
				List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
				params.add(new BasicNameValuePair("db", Constant.db));// 数据库
				params.add(new BasicNameValuePair("uid", "5")); // uid
				params.add(new BasicNameValuePair("note", noteStr)); // 博客内容内容
				params.add(new BasicNameValuePair("data_image", string)); // 图片列表
				params.add(new BasicNameValuePair("course_id", id)); // 图片列表
				String result = Tools.sendPost(Constant.answerCreate, params);
				Message message = new Message();
				try {
					if (result != null) {
						JsonNode jsonNode = om.readTree(result);
						String code = jsonNode.get("code").asText();
						System.out.println("code" + code);
						if (code.equals("200")) {
							message.what = 7;
							message.obj = result;

						} else {
							message.what = 6;// 登陆失败
						}
					} else {
						message.what = 9;// 无网络
					}
					handler.sendMessage(message);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					message.what = 10;
					handler.sendMessage(message);
				}
			};
		}.start();
	}

	@SuppressLint("HandlerLeak")
	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private int selectedPosition = -1;
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public void update() {
			loading();
		}

		public int getCount() {
			if (Bimp.tempSelectBitmap.size() == 9) {
				return 9;
			}
			return (Bimp.tempSelectBitmap.size() + 1);
		}

		public Object getItem(int arg0) {
			return null;
		}

		public long getItemId(int arg0) {
			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.item_published_grida,
						parent, false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.item_grida_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (position == Bimp.tempSelectBitmap.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				if (position == 9) {
					holder.image.setVisibility(View.GONE);
				}
			} else {
				holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position)
						.getBitmap());
			}

			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
		}

		Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					adapter.notifyDataSetChanged();
					break;
				}
				super.handleMessage(msg);
			}
		};

		public void loading() {
			new Thread(new Runnable() {
				public void run() {
					while (true) {
						if (Bimp.max == Bimp.tempSelectBitmap.size()) {
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
							break;
						} else {
							Bimp.max += 1;
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
						}
					}
				}
			}).start();
		}
	}

	public String getString(String s) {
		String path = null;
		if (s == null)
			return "";
		for (int i = s.length() - 1; i > 0; i++) {
			s.charAt(i);
		}
		return path;
	}

	protected void onRestart() {
		adapter.update();
		super.onRestart();
	}

	private static final int TAKE_PICTURE = 0x000001;
	private TextView tvSend;// 发送
	private EditText etBlog;// 问题内容
	private Spinner spinner;// 下拉菜单

	public void photo() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(openCameraIntent, TAKE_PICTURE);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			if (Bimp.tempSelectBitmap.size() < 9 && resultCode == RESULT_OK) {

				String fileName = String.valueOf(System.currentTimeMillis());
				Bitmap bm = (Bitmap) data.getExtras().get("data");
				FileUtils.saveBitmap(bm, fileName);

				ImageItem takePhoto = new ImageItem();
				takePhoto.setBitmap(bm);
				Bimp.tempSelectBitmap.add(takePhoto);
			}
			break;
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 下次进入的时候detext为空
			SharedPreferences sharedPreferences = getSharedPreferences(
					FILE_NAME, Activity.MODE_PRIVATE);
			edit = sharedPreferences.edit();
			edit.putString("Value", "");
			edit.commit();
			Toast.makeText(getApplicationContext(), "返回测试", 0).show();
			for (int i = 0; i < PublicWay.activityList.size(); i++) {
				if (null != PublicWay.activityList.get(i)) {
					PublicWay.activityList.get(i).finish();
				}
			}
			// finish()
			System.exit(0);
		}
		return true;
	}

	/**
	 * 获取课表
	 */
	private void getJsonText() {
		final Handler handler = new Handler() {
			private JSONObject jsonObject2;

			@SuppressLint("HandlerLeak")
			public void handleMessage(Message msg) {
				if (msg.what == 7) {
					String result = msg.obj.toString();
					try {
						JSONObject jsonObject = new JSONObject(result);
						JSONArray jsonArray = jsonObject.getJSONArray("data");
						lst = new ArrayList<CItem>();
						for (int i = 0; i < jsonArray.length(); i++) {
							// AnswerPer answerPer = new AnswerPer();
							jsonObject2 = (JSONObject) jsonArray.opt(i);
							String name = jsonObject2.get("name").toString();
							String integer = jsonObject2.get("id").toString();
							CItem cItem = new CItem();
							cItem.setValue(name);
							cItem.setID(integer);
							lst.add(cItem);
						}
						AdpterSpinner adpter = new AdpterSpinner(
								getApplicationContext(), lst);
						spinner.setAdapter(adpter);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else if (msg.what == 6) {
					// Toast.makeText(QuestionDetail.this, "帐号或密码错误", 0).show();
				} else if (msg.what == 10) {
					// Toast.makeText(QuestionDetail.this, "忘了联网了吧", 0).show();
				}

			}

		};
		new Thread() {
			public void run() {
				// 设置参数
				SharedPreferences sp = getSharedPreferences("UserId",
						MODE_PRIVATE);
				String uid = sp.getString("uid", "0");
				List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
				params.add(new BasicNameValuePair("db", Constant.db));
				params.add(new BasicNameValuePair("uid", "5")); // 密码
				String result = Tools.sendGet(Constant.courseList, params);
				Message message = new Message();
				try {
					if (result != null) {
						JsonNode jsonNode = om.readTree(result);
						code = jsonNode.get("code").asText();
						if (code.equals("200")) {
							message.what = 7;
							message.obj = result;
						} else {
							message.what = 6;// 登陆失败
						}
					} else {
						message.what = 9;// 无网络
					}
					handler.sendMessage(message);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					message.what = 10;
					handler.sendMessage(message);
				}
			};
		}.start();
	}

	/**
	 * 页面返回调用onpause保存数据
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// 保存问题内容
		SharedPreferences sharedPreferences = getSharedPreferences(FILE_NAME,
				Activity.MODE_PRIVATE);
		String note = sharedPreferences.getString("Value", "");
		etBlog.setText(note);
		/**
		 * 得到博客内容、图片列表 传输数据？
		 */
		tvSend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				noteStr = etBlog.getText().toString().trim();
				if (!"".equals(noteStr) || string.length() != 0) {
					sendJsontoNet();
					noteStr = etBlog.getText().toString().trim();
					SharedPreferences sharedPreferences = getSharedPreferences(
							FILE_NAME, Activity.MODE_PRIVATE);
					edit = sharedPreferences.edit();
					edit.putString("Value", "");
					edit.commit();
					finish();
				} else {
					Toast.makeText(getApplicationContext(), "您好，内容不能为空！",
							Toast.LENGTH_SHORT).show();
				}

			}
		});
		spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View arg1,
					int position, long arg3) {

				String value = lst.get(position).getValue();
				id = lst.get(position).getID();
				Toast.makeText(MainActivitypoth.this, "你点击的是:" + value,
						Toast.LENGTH_SHORT).show();
				Log.d("mark", "onItemSelected() is invoked!");
				parent.setVisibility(View.VISIBLE);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}

	// @Override
	// protected void onSaveInstanceState(Bundle outState) {
	// // TODO Auto-generated method stub
	// super.onSaveInstanceState(outState);
	// noteStr = etBlog.getText().toString().trim();
	// SharedPreferences sharedPreferences = getSharedPreferences(FILE_NAME,
	// Activity.MODE_PRIVATE);
	// edit = sharedPreferences.edit();
	// edit.putString("Value", noteStr);
	// edit.commit();
	// }
	/**
	 * 返回键
	 */
	// @Override
	// public boolean onKeyDown(int keyCode, KeyEvent event) {
	// if ((keyCode == KeyEvent.KEYCODE_BACK)) {
	// System.out.println("按下了back键   onKeyDown()");
	// Intent intent = new Intent();
	// // intent.putExtra("addContent", str);
	// // intent.putExtra("position_back", position);
	// setResult(RESULT_OK, intent);
	// finish();
	// return true;
	// } else {
	// return super.onKeyDown(keyCode, event);
	// }
	//
	// }
}
